package com.mingqijia.gassafety.webserver.utils;

import com.mingqijia.gassafety.webserver.service.ConsumerService;
import com.mingqijia.gassafety.webserver.service.impl.ConsumerServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpelUtil {
    @Autowired
    public void setConsumerService(ConsumerService consumerService) {
        this.consumerService = consumerService;
    }

    static ConsumerService consumerService;



    /**
     * 用于SpEL表达式解析.
     */
    private static SpelExpressionParser parser = new SpelExpressionParser();


    public static String parseSpEL(String spELString, Object[] param, String[] parameterNames) {
        try {
            if (StringUtils.isBlank(spELString)) {
                return spELString;
            }
            if (param == null || param.length == 0) {
                return spELString;
            }
            // 解析过后的Spring表达式对象
            Expression expression = parser.parseExpression(spELString);
            // spring的表达式上下文对象
            EvaluationContext context = new StandardEvaluationContext();
            context.setVariable("consumerService", consumerService);
            // 给上下文赋值
            for (int i = 0; i < param.length; i++) {
                context.setVariable(parameterNames[i], param[i]);
            }

            return expression.getValue(context).toString();
        } catch (Exception e) {
            log.info("解析异常:{},spEL:{},",e.getMessage(),spELString);
            return spELString;
        }
    }
}
